package com.cherrypt.api.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cherrypt.api.common.exception.TipException;
import com.cherrypt.api.core.dao.LevelDao;
import com.cherrypt.api.core.service.LevelService;
import com.cherrypt.api.model.dataobject.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author intent
 * @date 2019/8/5 14:22
 * @about <link href='http://zzyitj.xyz/'/>
 */
@Service
public class LevelServiceImpl extends ServiceImpl<LevelDao, Level> implements LevelService {
    private static final Logger logger = LoggerFactory.getLogger(LevelServiceImpl.class);

    @Autowired
    private ListOperations<String, Object> listOperations;

    @Value("${api.config.redis.level.value}")
    private String levelValue;

    @Override
    public void saveRedisLevelList(List<Level> levelList) {
        levelList.forEach(level -> {
            listOperations.leftPush(levelValue, level);
        });
    }

    @Override
    public List<Level> getRedisLevelList() {
        List<Level> levelList = new ArrayList<>();
        List<Object> list = listOperations.range(levelValue, 0, -1);
        if (list != null && list.size() > 0) {
            for (Object o : list) {
                levelList.add((Level) o);
            }
        }
        return levelList;
    }

    @Override
    public List<Level> getLevelList() throws TipException {
        List<Level> levelList = getRedisLevelList();
        if (levelList == null || levelList.size() == 0) {
            levelList = list();
            if (levelList.size() != 0) {
                saveRedisLevelList(levelList);
                logger.info("缓存LevelList到Redis, {}", levelList.size());
            }
        }
        return levelList;
    }
}
